<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>table模块快速使用</title>
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<body>
<form class="layui-form layui-form-pane" action="">

</form>
<div class="layui-row " style="padding-left: 18px; padding-top: 10px;">

    <div class="layui-form layui-form-pane" lay-filter="testForm">
        <div class=" layui-form-item layui-inline" style="margin-bottom: 0px;">
            <label class="layui-form-label">查询司机</label>
            <div class="layui-inline">
                <input id="customer" class="layui-input" type="text" placeholder="名称/车牌号/车型..."/>
            </div>
        </div>
        <div class="layui-inline">
            <button id="btnSearch" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i></button>
            <button id="btnReset" class="layui-btn layui-btn-normal" title="点击重置查询条件"><i
                    class="layui-icon">&#xe639;</i></button>
        </div>
    </div>
</div>
<table class="layui-hide" id="testTable" lay-filter="testTable"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button id="btnBatchDelete" class="layui-btn layui-btn-sm layui-btn-danger">批量删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
        <button class="layui-btn layui-btn-sm" id="add">新增</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" id="edit" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script src="../layui/layui.js" charset="utf-8"></script>

<script>

    // 要使用的layui模块
    layui.use(['layer', 'form', 'table', 'laydate', 'element'], function () {
        var layer = layui.layer; // 获得layer模块
        var form = layui.form; // 获得form模块
        var table = layui.table; // 获得table模块
        var laydate = layui.laydate; // 获得laydate模块
        var element = layui.element; // 获得element模块（和导航、tab等有关）
        var $ = layui.$; // 调用JQuery方法时
        var laytpl = layui.laytpl;

        //更新 lay-filter="test2" 所在容器内的全部 select 状态
        // form.render('select', 'test2');

        laydate.render({
            elem: '#birthday'
        });

        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            }
            , word: [
                /^[A-Za-z0-9]+$/
                , '请输入正确的编号'
            ]
            , number: [
                /^[0-9]+(.[0-9]{1,5})?$/
                , '请输入正确的数字'
            ]
            , name: [
                /^[\u4E00-\u9FA5A-Za-z]+$/
                , '请填写正确的姓名'
            ]
            , carNo: [
                /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
                , '请输入正确的车牌号'
            ]
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });
        //第一个实例
        var tableIns = table.render({
            elem: '#testTable' // 给table设置id或class，方便layui调用该元素
            , height: 'full-200' // 窗口高度-100
            , url: '/application/searchDriver' // 数据接口
            // ,method: 'post' //如果无需自定义HTTP类型，可不加该参数
            , page: true // 开启分页
            , limit: 20 // 默认页大小
            , limits: [10, 20, 30, 50, 100] //自定义可选分页大小
            , cellMinWidth: 80 // 全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , skin: 'line' // 行边框风格
            // ,even: true // 开启隔行背景
            // ,size: 'sm' // 小尺寸的表格
            , totalRow: true // 开启合计功能
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            , defaultToolbar: ['filter', 'exports', 'print', { // 列过滤、导出按钮、打印按钮
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: '代收结算表'// 表名
            // 列信息
            , cols: [[ //表头
                // {type:'radio', fixed: 'left'} // 开启单选框
                {type: 'checkbox', fixed: 'left'} // 开启复选框
                , {field: 'driverName', title: '司机名称', fixed: 'left', sort: true, totalRowText: '合计'}
                , {field: 'idCard', title: '身份证号'}
                , {field: 'mobile', title: '手机', totalRow: false}
                , {field: 'gender', title: '性别', totalRow: false}
                , {field: 'birthday', title: '出生日期', totalRow: false}
                , {field: 'state', title: '状态'}
                , {field: 'carNo', title: '车牌号', totalRow: true}
                , {field: 'carType', title: '车型', totalRow: true}
                , {field: 'driveLicence', title: '驾驶证', totalRow: true}
                , {field: 'carWidth', title: '车厢宽度', totalRow: true}
                , {field: 'goodsHeight', title: '载物高度', totalRow: true}
                , {field: 'carFrameNo', title: '车架号', totalRow: false}
                , {field: 'engineNo', title: '发动机号', totalRow: false}
                , {field: 'carLength', title: '车厢长度', totalRow: true}
                , {field: 'allowCarryVolume', title: '准载体积', totalRow: true}
                , {field: 'allowCarryWeight', title: '准载重量', totalRow: true}
                , {field: 'remark', title: '备注', totalRow: true}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
            ]]
        });

        $("#add").on('click',function () {
            $("#driver")[0].reset();
            layer.open({
                //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                type: 1,
                title: "添加司机信息",
                area: ['800px','600px'],
                btn:['取消'],
                content: $("#updateDriver")  //引用的弹出层的页面层的方式加载修改表单
            });
            add();
        });

        function add() {
            form.on('submit(ok)', function (data) {
                $.ajax({
                    url: '/application/addDriver',
                    type: 'POST',
                    data: {
                        'driverName': data.field.driverName
                        ,'idCard': data.field.idCard
                        ,'mobile': data.field.mobile
                        ,'birthday': data.field.birthday
                        ,'state': data.field.state
                        ,'carNo': data.field.carNo
                        ,'allowCarryVolume': data.field.allowCarryVolume
                        ,'allowCarryWeight': data.field.allowCarryWeight
                        ,'carType': data.field.carType
                        ,'carLength': data.field.carLength
                        ,'driveLicence': data.field.driveLicence
                        ,'carWidth': data.field.carWidth
                        ,'goodsHeight':data.field.goodsHeight
                        ,'carFrameNo': data.field.carFrameNo
                        ,'engineNo': data.field.engineNo
                        ,'remark': data.field.remark
                    },
                    success: function (result) {
                        var code = result.code;
                        if (code == 0) {
                            layer.closeAll("Loading");
                            layer.load(2);
                            layer.msg(result.msg, {icon: 6});
                        } else {
                            layer.msg(result.msg, {icon: 5})
                        }
                    }
                });
            })
        };
        // 查询用对象
        var MgrSettle = {
            tableId: "testTable",    //表格id
            condition: {
                customer: "",
                balanceDate: ""
            }
        };

        // 查询请求内容
        MgrSettle.search = function () {
            var queryData = {};
            queryData['customer'] = $("#customer").val();
            queryData['goodsBillCode'] = $("#goodsBillCode").val();
            var balanceDate = $("#balanceDate-start").val()+' - '+$("#balanceDate-end").val();
            queryData['balanceDate'] = balanceDate;
            table.reload(MgrSettle.tableId, {where: queryData});
        };
        // 点击查询按钮
        $('#btnSearch').click(function () {
            MgrSettle.search();
        });
        // 重置查询条件
        $("#btnReset").click(function () {
            $("#customer").val("");
            $("#goodsBillCode").val("");
            $("#balanceDate-start").val("");
            $("#balanceDate-end").val("");
            form.render(null, 'testForm');
        });

        //!!! 注意：批量删除按钮在script里，必须使用以下格式才能不出点击重置后无效的bug
        //批量删除
        $('body').on('click', '#btnBatchDelete', function() {
            var checkStatus = table.checkStatus('testTable'),
                data = checkStatus.data,
                keys ="";
            if(data.length > 0) {
                for (var i in data) {
                    keys+=data[i].ddid+",";
                }
                keys = keys.substring(0,keys.length-1);
                // console.log(keys);
                layer.confirm('确定删除选中的数据？',{title: '提示信息'},function(index) {
                    $.post('/application/deleteList'+keys,function(data){
                        if (data.code==0) {
                            tableIns.reload();
                            layer.msg(data.msg);
                            layer.close(index);
                        }
                    })
                });
            }else{
                layer.msg("请先选择需要删除的数据");
            }
        });
        /*        $("#btnBatchDelete").click(function () {

                });*/




        // 监听行双击事件
        table.on('rowDouble(testTable)', function (obj) {
            console.log(obj.tr) //得到当前行元素对象
            console.log(obj.data) //得到当前行数据
        });

        table.on('checkbox(testTable)', function (obj) {

            // 复选框监听
            console.log(obj.checked); //当前是否选中状态
            console.log(obj.data); //选中行的相关数据
            console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
        });

        //头工具栏事件
        table.on('toolbar(testTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：' + data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选' : '未全选');
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        //监听工具条
        table.on('tool(testTable)', function (obj) {
            var data = obj.data;
            var did = data['diid'];
            if (obj.event === 'detail') {
                layer.msg('ID：' + data.id + ' 的查看操作');
            } else if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                   $.ajax({
                       url: "/application/deleteOneDriver",
                       type: "POST",
                       data : {
                           did: did
                       },
                       success: function (result) {
                           var code = result.code;
                           if(code == 0){
                               obj.del();
                               //关闭弹框
                               layer.closeAll();
                               layer.msg(result.msg,{icon: 6})
                           }else {
                               layer.msg(result.msg,{icon: 5})
                           }
                       }
                   })
                });
            } else if (obj.event === 'edit') {
                var data = obj.data;    //获得当前行数据
                var did = data['diid'];
                // alert(did);
                {
                    $("#driverName").val(data['driverName']);
                    $("#idCard").val(data['idCard']);
                    $("#mobile").val(data['mobile']);
                    $("#gender").val(data['gender']);
                    $("#birthday").val(data['birthday']);
                    $("#state").val(data['state']);
                    $("#carNo").val(data['carNo']);
                    $("#allowCarryVolume").val(data['allowCarryVolume']);
                    $("#allowCarryWeight").val(data['allowCarryWeight']);
                    $("#carType").val(data['carType']);
                    $("#carLength").val(data['carLength']);
                    $("#driveLicence").val(data['driveLicence']);
                    $("#carWidth").val(data['carWidth']);
                    $("#goodsHeight").val(data['goodsHeight']);
                    $("#carFrameNo").val(data['carFrameNo']);
                    $("#engineNo").val(data['engineNo']);
                    $("#remark").val(data['remark']);
                }
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "修改司机信息",
                    area: ['800px','600px'],
                    btn:['取消'],
                    content: $("#updateDriver")  //引用的弹出层的页面层的方式加载修改表单
                });
                //动态向表传递赋值
                setFormValue(did,obj);
            }
        });
        //监听弹出框表单提交，message修啊界面的表单数据，sumbit（是修改按钮的而绑定）
        function setFormValue(did,obj) {
            form.on('submit(ok)',function (data) {
                console.log(data.field);
                $.ajax({
                    url: '/application/updateOneDriver',
                    type: 'POST',
                    data: {
                        'did': did,
                        'driverName': data.field.driverName
                        ,'idCard': data.field.idCard
                        ,'mobile': data.field.mobile
                        ,'gender':  data.field.gender
                        ,'birthday': data.field.birthday
                        ,'state': data.field.state
                        ,'carNo': data.field.carNo
                        ,'allowCarryVolume': data.field.allowCarryVolume
                        ,'allowCarryWeight': data.field.allowCarryWeight
                        ,'carType': data.field.carType
                        ,'carLength': data.field.carLength
                        ,'driveLicence': data.field.driveLicence
                        ,'carWidth': data.field.carWidth
                        ,'goodsHeight':data.field.goodsHeight
                        ,'carFrameNo': data.field.carFrameNo
                        ,'engineNo': data.field.engineNo
                        ,'remark': data.field.remark
                    },
                    success:function (result) {
                        console.log(result);
                        var code = result.code;
                        if (code == 0){
                            layer.closeAll("Loading");
                            layer.load(2);
                            layer.msg(result.msg,{icon: 6});
                            setTimeout(function () {
                                obj.update({
                                    'driverName': data.field.driverName
                                    ,'idCard': data.field.idCard
                                    ,'mobile': data.field.mobile
                                    ,'gender':  data.field.gender
                                    ,'birthday': data.field.birthday
                                    ,'state': data.field.state
                                    ,'carNo': data.field.carNo
                                    ,'allowCarryVolume': data.field.allowCarryVolume
                                    ,'allowCarryWeight': data.field.allowCarryWeight
                                    ,'carType': data.field.carType
                                    ,'carLength': data.field.carLength
                                    ,'driveLicence': data.field.driveLicence
                                    ,'carWidth': data.field.carWidth
                                    ,'goodsHeight':data.field.oodsHeight
                                    ,'carFrameNo': data.field.carFrameNo
                                    ,'engineNo': data.field.engineNo
                                    ,'remark': data.field.remark
                                });
                                //修改成功不进行跳转
                                layer.closeAll();//关闭所有的弹出层
                            });
                        }else {
                            layer.msg(result.msg,{inco:5});
                        }
                    }
                });
                return false;
            })
        }
    });

</script>
<!--这是弹出层的表单信息
表单的id用于表单的选择，style是在本页隐藏，只有点击编辑才会弹出-->
<div id="updateDriver" style="display: none;">
    <fieldset class="layui-elem-field layui-field-title" lay-filter="driver" style="margin-top: 50px;">
        <legend>司机信息填写</legend>
    </fieldset>
    <form class="layui-form layui-form-pane" id="driver" action="" style="margin-left: 50px">
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-inline">
                <input type="text" id="driverName" name="driverName" lay-verify="name" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">出生日期</label>
                <div class="layui-input-block">
                    <input type="text" id="birthday" name="birthday"  autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">手机号码</label>
                <div class="layui-input-inline">
                    <input type="tel" id="mobile" name="mobile" lay-verify="required|phone" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">车牌号</label>
                <div class="layui-input-block">
                    <input type="text" id="carNo" name="carNo" lay-verify="carNO"  autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">准载体积</label>
                <div class="layui-input-inline">
                    <input type="tel" id="allowCarryVolume" name="allowCarryVolume" lay-verify="required|number" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">准载重量</label>
                <div class="layui-input-inline">
                    <input type="tel" id="allowCarryWeight" name="allowCarryWeight" lay-verify="required|number" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">车厢长度</label>
                <div class="layui-input-block">
                    <input type="text" name="carLength" id="carLength" lay-verify="required|number" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">车厢宽度</label>
                <div class="layui-input-inline">
                    <input type="tel" name="carWidth" id="carWidth" lay-verify="required|number" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">载物高度</label>
                <div class="layui-input-inline">
                    <input type="tel" id="goodsHeight" name="goodsHeight" lay-verify="required|number" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">驾驶证</label>
                <div class="layui-input-block">
                    <input type="text" id="driveLicence" name="driveLicence" lay-verify="identity"  autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">车架号</label>
                <div class="layui-input-inline">
                    <input type="tel" id="carFrameNo" name="carFrameNo" lay-verify="required|word" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">发动机号</label>
                <div class="layui-input-inline">
                    <input type="tel" id="engineNo" name="engineNo" lay-verify="required|word" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item" pane="">
            <label class="layui-form-label">车型</label>
            <div class="layui-input-block">
                <input type="radio" name="carType" value="4.2m" title="4.2m" checked="">
                <input type="radio" name="carType" value="其他" title="其他">
            </div>
        </div>
        <div class="layui-form-item" pane="">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-inline">
                <select name="state" id="state">
                    <option value="">请选择状态</option>
                    <option value="待运" selected="">待运</option>
                    <option value="运输中">运输中</option>
                    <option value="完成运输">完成运输</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">身份证号码</label>
            <div class="layui-input-block">
                <input type="text" id="idCard" name="idCard" lay-verify="identity" placeholder="请认真填写" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea  id="remark" name="remark" placeholder="请输入内容" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn" lay-submit="" lay-filter="ok" >确认提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </form>
</div>
</body>
</html>